package com.example.activity

import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.BaseAdapter
import android.widget.GridView
import android.widget.ImageView
import androidx.annotation.RequiresApi
import java.util.*

class ChooseHeadThumbActivity : AppCompatActivity() {

    private val pictures:Array<Int> = arrayOf(
        R.drawable.head_01,
        R.drawable.head_02
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_choose_head_thumb)

        val gridView = findViewById<GridView>(R.id.gridView)
        gridView.adapter = ImageAdaptor()

        gridView.setOnItemClickListener{ parent: AdapterView<*>, view: View, position: Int, id: Long ->
            val bundle = Bundle()
            bundle.putInt("imageId",pictures[position])
            intent.putExtras(bundle)
            //设置返回码，一般和请求吗设置为一样，以至于可以辨别
            setResult(0x11,intent)
            finish()
        }

    }

    inner class ImageAdaptor: BaseAdapter() {
        @RequiresApi(Build.VERSION_CODES.N)
        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
            val imageView: ImageView?
            if (Objects.isNull(convertView)){
                imageView = ImageView(this@ChooseHeadThumbActivity)
                imageView.layoutParams = ViewGroup.LayoutParams(200,200)
                imageView.scaleType = ImageView.ScaleType.CENTER_CROP
            }else{
                imageView = convertView as ImageView
            }
            imageView.setImageResource(pictures[position])
            return imageView
        }

        override fun getItem(position: Int): Any? {
            return position
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getCount(): Int {
            return pictures.size
        }
    }
}